﻿//-----------------------------------------------------------------------
// <copyright file="WebflowResult.cs" company="Sławomir Rosiek">
//     Copyright (c) Sławomir Rosiek. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Rosieks.Web.Flow
{
    using System.Web.Mvc;

    public class WebflowResult : ActionResult
    {
        private readonly object model;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:WebflowResult"/> class.
        /// </summary>
        /// <param name="actionName"></param>
        public WebflowResult(string actionName)
            : this(actionName, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:WebflowResult"/> class.
        /// </summary>
        public WebflowResult()
            : this(null, null)
        {
        }

        public WebflowResult(object model)
            : this(null, model)
        {
        }

        public WebflowResult(string actionName, object model)
        {
            this.model = model;
            this.ActionName = actionName;
        }

        public string ActionName
        {
            get;
            private set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (this.model != null)
            {
                context.Controller.ViewData.Model = this.model;
            }

            var webflowContext = WebflowContext.GetCurrent(context.HttpContext);

            var currentElementType = webflowContext.CurrentElement.GetType();

            var resultAdapterType = WebflowElementResultProvider.Adapters[currentElementType];

            var resultAdapter = resultAdapterType();

            var result = resultAdapter.CreateResult(webflowContext.CurrentElement, context);

            result.ExecuteResult(context);
        }
    }
}
